package com.swipemaster;

import java.util.ArrayList;
import java.util.Timer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;

public class GameRenderer implements GLSurfaceView.Renderer
{
	/** The higher the squares are bigger. */
	private final static float SCREEN_TO_SQUARE_SIZE_RATIO = 0.05f;
	private final static int TICK_PERIOD_MS = 50;
	public static int mScreenWidth, mScreenHeight;
	public static int mSquareSize;
	private TouchSurfaceView mTouchSurfaceView;
	private ArrayList<Square> mEnemies = new ArrayList<Square>();

	public GameRenderer(TouchSurfaceView touchSurfaceView, int width, int height)
	{
		mTouchSurfaceView = touchSurfaceView;
		mScreenWidth = width;
		mScreenHeight = height;
		mSquareSize = (int) (Math.min(width, height) * SCREEN_TO_SQUARE_SIZE_RATIO);
		Timer timer = new Timer();
		timer.schedule(new UpdateTimeTask(this), 0, TICK_PERIOD_MS);
	}

	public void onDrawFrame(GL10 gl)
	{
		// Clear screen and depth buffer.
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		// Reset the modelview matrix.
		gl.glLoadIdentity();
		// Draw all squares.
		synchronized (mEnemies)
		{
			for (Square enemy : mEnemies)
			{
				enemy.draw(gl);
			}
		}
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height)
	{
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		// Adjust OpenGL positioning to screen positioning.
		gl.glOrthof(0, width, height, 0, -1, 1);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config)
	{
		// Clear with white color, not default black.
		gl.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
	}

	public void addSquare(int x, int y)
	{
		Square square = new Square(mSquareSize, 1.0f, 0.0f, 0.0f);
		square.setXAndY(x, y);
		synchronized (mEnemies)
		{
			mEnemies.add(square);
		}
	}

	/**
	 * Will be called periodically. Here we can move mEnemies etc.
	 */
	public void tick()
	{
		for (Square enemy : mEnemies)
		{
			enemy.move();
		}
		mTouchSurfaceView.requestRender();
	}
	
	public int getNumberOfEnemies()
	{
		return mEnemies.size();
	}
}
